package com.newtouch.krd_app;

import static java.util.stream.Collectors.toList;

import android.annotation.SuppressLint;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ViewSwitcher;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.bumptech.glide.Glide;
import com.google.android.gms.common.util.CollectionUtils;
import com.google.gson.Gson;
import com.hjq.http.EasyHttp;
import com.hjq.http.body.JsonBody;
import com.hjq.http.listener.HttpCallback;
import com.hjq.http.listener.OnDownloadListener;
import com.hjq.http.model.HttpMethod;
import com.hjq.toast.ToastUtils;
import com.jakewharton.processphoenix.ProcessPhoenix;
import com.jyn.marqueetextview.MarqueeView;
import com.newtouch.krd_app.http.api.AddTerminalApi;
import com.newtouch.krd_app.http.api.NoticeApi;
import com.newtouch.krd_app.http.api.TerminalApi;
import com.newtouch.krd_app.http.model.Group;
import com.newtouch.krd_app.http.model.HttpData;
import com.newtouch.krd_app.http.model.Item;
import com.newtouch.krd_app.http.websocket.WebSocketUtil;
import com.newtouch.krd_app.util.BaseUrlUtil;
import com.newtouch.krd_app.util.ControllerInterface;
import com.newtouch.krd_app.util.CrashHandler;
import com.newtouch.krd_app.util.DeviceUtil;
import com.newtouch.krd_app.util.SPUtils;
import com.newtouch.krd_app.view.WidgetView;
import com.newtouch.krd_app.view.WidgetViewImage;
import com.newtouch.krd_app.view.WidgetViewPdf;
import com.newtouch.krd_app.view.WidgetViewWeb;
import com.newtouch.krd_app.view.WidgetViewijkVideo;
import com.newtouch.krd_app.view.adapter.ExpandableListAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 *    author : TQ
 *    time   : 2023/02/13
 *    desc   : 主界面类
 */
public class MainActivity extends BaseActivity {

    private ViewSwitcher viewSwitcher;//文件播放切换器
    private MarqueeView marqueeView;//跑马灯

    private ControllerInterface controllerInterface;//播放控制回调接口
    private int currentPosition;//下个播放的文件
    private TerminalApi.Bean data;//播放的数据
    private WidgetView currentWidget;//当前播放的控件
    private ExpandableListView expandableListView;//详细面板
    private ArrayList<Group> gData;
    private ArrayList<ArrayList<Item>> iData;
    private ExpandableListAdapter expandableListAdapter;
    private long logTime;//上次运行时间
    private LinearLayout ll_detail,ll_input;
    private int downLoadPostion = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewSwitcher = this.findViewById(R.id.viewSwitcher);
        ImageView imageView = findViewById(R.id.imageView);
        marqueeView = findViewById(R.id.marqueeView);
        expandableListView = findViewById(R.id.exlist);
        ll_detail = findViewById(R.id.ll_detail);
        ll_input = findViewById(R.id.ll_input);
        EditText et_ip = findViewById(R.id.et_ip);
        Button btn_sure = findViewById(R.id.btn_sure);

        Glide.with(MainActivity.this)
                .load(R.mipmap.logo2)
                .into(imageView);
        imageView.setOnClickListener(view -> setData());

        NoticeApi.Bean notceapi = (NoticeApi.Bean) SPUtils.get(this,"NoticApi",null);
        if (notceapi !=null){
            marqueeView.setText(notceapi.getNotice());
        }else{
            marqueeView.setText("Get 请求成功，请看日志 Get 请求成功，请看日志=");
        }
        ll_detail.setOnClickListener(view -> ll_detail.setVisibility(View.GONE));
        ll_input.setOnClickListener(view -> ll_input.setVisibility(View.GONE));
        btn_sure.setOnClickListener(view -> {
            String ip = et_ip.getText().toString();
            if (TextUtils.isEmpty(ip)){
                ToastUtils.show("ip端口不能为空");
                return;
            }
            BaseUrlUtil.getInstance().setCurrentUrl(ip);
            ll_input.setVisibility(View.GONE);
            InputMethodManager imm = (InputMethodManager) MainActivity.this.getSystemService(MainActivity.this.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(et_ip.getWindowToken(), 0);
        });

        getAddTerminalApi();
        toShowExlist();
        getLogTime();
        getNoticeApi();
        getTerminalApi();
        //控制接口类，各个组件播放完成回调，websocket进行回调
        controllerInterface = new ControllerInterface() {
            //组件播放结束回调
            @Override
            public void playEnd() {
                runOnUiThread(() -> playNext());

            }
            //组件播放开始回调
            @Override
            public void playStart() {
                if (data == null){
                    getNoticeApi();
                    getTerminalApi();
                }else if (data.getFiles()==null){
                    getNoticeApi();
                    getTerminalApi();
                }else if (data.getFiles().size() == 0){
                    getNoticeApi();
                    getTerminalApi();
                }
            }
            //数据更新，websocket 数据来了时进行回调
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void dataUpdate(TerminalApi.Bean mdata) {
                if (mdata != null){
                    EasyHttp.cancel();
                    data = mdata;
                    getNoticeApi();
                    playReStart();
                    downLoadFileStart();
                }

            }

            @Override
            public void notice() {
                getNoticeApi();
            }

        };
        WebSocketUtil.getInstance().initWebSocketUtil(MainActivity.this,controllerInterface);

    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        getNoticeApi();
        getTerminalApi();
    }

    /**
     * 添加客户端
     */

    private void getAddTerminalApi() {
        HashMap<String, String> parmas = new HashMap<>();
        parmas.put("terminalCode", BaseUrlUtil.getInstance().getMac());
        parmas.put("terminalResolution",DeviceUtil.getScreenWidth(this)+" x "+DeviceUtil.getScreenHeight(this));
        parmas.put("terminalSpec",DeviceUtil.getPhoneModel());
        EasyHttp.post(this)
                .api(new AddTerminalApi())
                .body(new JsonBody(new Gson().toJson(parmas)))
                .request(new HttpCallback<HttpData<AddTerminalApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<AddTerminalApi.Bean> result) {
                        Log.e("getAddTerminalApi","添加Mac成功");
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                    }
                });
    }

    /**
     * 获取跑马灯数据
     */
    private void getNoticeApi() {
        EasyHttp.get(this)
                .api(new NoticeApi())
                .request(new HttpCallback<HttpData<NoticeApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<NoticeApi.Bean> result) {
                        SPUtils.put(MainActivity.this,"NoticApi",result.getData());
                        if (result.getData()!=null && result.getData().getTitle()!=null){
                            marqueeView.setText(result.getData().getTitle());
                            SPUtils.put(MainActivity.this,"Notice",result.getData().getTitle());
                        }else{
                            marqueeView.setText("Get 请求成功，请看日志");
                        }

                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                        if (!TextUtils.isEmpty((String) SPUtils.get(MainActivity.this,"Notice",""))){
                            marqueeView.setText((String) SPUtils.get(MainActivity.this,"Notice",""));
                        }
                    }
                });
    }

    /**
     * 获取播放数据，触发playReStart
     */
    private void getTerminalApi() {
        EasyHttp.get(this)
                .api(new TerminalApi())
                .request(new HttpCallback<HttpData<TerminalApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<TerminalApi.Bean> result) {
                        data = result.getData();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            downLoadFileStart();
                        }
                        playReStart();
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                        String locData = (String) SPUtils.get(MainActivity.this,"locData","");
                        if (!TextUtils.isEmpty(locData)){
                            data = new Gson().fromJson(locData,TerminalApi.Bean.class);
                            playReStart();
                        }else{
                            ToastUtils.show("没有本地缓存文件，请联网");
                        }
                    }
                });
    }

    /**
     * 触发播放开始
     */
    private void playReStart(){
        if (data!=null && data.getFiles()!=null && data.getFiles().size()>0){
            currentPosition = 0;
            runOnUiThread(() -> playNext());

        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void downLoadFileStart(){
        downLoadPostion = 0;
        downloadFile();
    }

    /**
     * 播放下一个文件
     */
    private void playNext(){
        Log.e("TAG", "playNext: "+currentPosition );
        if (data!=null && data.getFiles()!=null && data.getFiles().size()>0 && currentPosition < (data.getFiles().size())){
            if (currentWidget!=null){
                currentWidget.terminatePlay();
            }
            TerminalApi.Bean.FilesDTO item = data.getFiles().get(currentPosition);
            Log.e("playNext",item.getFileType());
            CrashHandler.getInstance().towriteLog("playNext()"+"currentPosition:"+currentPosition+"fileType:"+item.getFileType());
//            ToastUtils.show("即将播放："+item.getFileName()+"文件路径："+item.getFilePath());
            switch (item.getFileType()){
                case "png":
                case "jpg":
                case "jpeg":
                    currentWidget = new WidgetViewImage(this,controllerInterface);
                    break;
                case "pdf":
                    if (item.getPicFiles().size() == 1){
                        currentWidget = new WidgetViewImage(this,controllerInterface);
                    }else{
                        currentWidget = new WidgetViewPdf(this,controllerInterface);
                    }
                    break;
                case "xlsx":
                case "docx":
                    currentWidget = new WidgetViewWeb(this,controllerInterface);
                    break;
                case "mp4":
                    currentWidget = new WidgetViewijkVideo(this,controllerInterface);
                    break;

            }

            runOnUiThread(() -> {
                currentWidget.setFilesDTO(item);
                viewSwitcher.removeAllViews();
                viewSwitcher.addView(currentWidget.getView());
                currentWidget.startPlay();
                currentPosition++;
            });

        }else {
            playReStart();
        }
    }

    /**
     * 初始化展示详细
     */
    private void toShowExlist() {
        gData = new ArrayList<>();
        iData = new ArrayList<>();
        expandableListAdapter = new ExpandableListAdapter(gData,iData,this);
        expandableListView.setAdapter(expandableListAdapter);

        //为列表设置点击事件
        expandableListView.setOnChildClickListener((parent, v, groupPosition, childPosition, id) -> {
            if (groupPosition == 2&&childPosition==0){
                currentPosition = currentPosition-1;
                playNext();
            }else if (groupPosition == 2&&childPosition==1){
                ProcessPhoenix.triggerRebirth(MainActivity.this);
            }else if (groupPosition == 3&&childPosition==1){//
                ll_detail.setVisibility(View.GONE);
                ll_input.setVisibility(View.VISIBLE);

            }else if (groupPosition == 2&&childPosition==2){//清除缓存

            }
            return true;
        });

        expandableListView.setOnGroupExpandListener(groupPosition -> {
            // TODO Auto-generated method stub
            for (int i = 0; i < expandableListAdapter.getGroupCount(); i++) {
                if (groupPosition != i) {
                    expandableListView.collapseGroup(i);
                }
            }

        });
    }

    /**
     * 设置详细数据
     */
    private void setData() {
        gData.clear();
        iData.clear();
        //数据准备
        gData.add(new Group("文件播放相关"));
        gData.add(new Group("系统信息"));
        gData.add(new Group("相关操作"));
        gData.add(new Group("环境切换及配置（重启生效）"));
        gData.add(new Group("日志"));


        ArrayList<Item> lData = new ArrayList<>();
        lData.add(new Item("网络状态："+(DeviceUtil.isNetworkConnected(this)? "已连接" : "断开")));
        if (currentWidget!=null){
            lData.add(new Item("当前文件类型："+currentWidget.getFilesDTO().getFileType()));
            lData.add(new Item("当前第"+ currentPosition +"个文件："+currentWidget.getFilesDTO().getFilePath()));
            lData.add(new Item("当前文件播放时长："+ toMinute(currentWidget.getDuration()) +"分钟"));
            lData.add(new Item("共有文件数："+ (data==null?"0":data.getFiles().size()+"")));
        }else{
            lData.add(new Item("当前文件类型："));
            lData.add(new Item("当前第"+ currentPosition +"个文件："));
            lData.add(new Item("当前文件播放时长：分钟"));
            if (data!=null&&data.getFiles()!=null){
                lData.add(new Item("共有文件数："+ (data==null?"0":data.getFiles().size()+"")));
            }else {
                lData.add(new Item("共有文件数：0"));
            }

        }

        lData.add(new Item("是否读取本地缓存文件："+(BaseUrlUtil.getInstance().isConnect?"否":"是")));
        iData.add(lData);
        //AP组
        lData = new ArrayList<>();
        lData.add(new Item( "Mac地址："+DeviceUtil.getMac()));
        lData.add(new Item( "App名称：安全融媒体平台"));
        iData.add(lData);
        //TANK组
        lData = new ArrayList<>();
        lData.add(new Item( "重新加载当前文件"));
        lData.add(new Item( "重启设备"));
        lData.add(new Item( "清除缓存"));
        iData.add(lData);

        lData = new ArrayList<>();
        lData.add(new Item( "118"));
        lData.add(new Item( "自定义"));
        lData.add(new Item( "单机模式"));
        lData.add(new Item( "是否开启重启模式 分钟/次"));
        iData.add(lData);

        lData = new ArrayList<>();
        lData.add(new Item( "上次运行时长："+toMinute(logTime)+" 分钟"));
        iData.add(lData);

        expandableListAdapter.setgData(gData,iData);
        ll_detail.setVisibility(View.VISIBLE);
        expandableListView.expandGroup(gData.size()-2);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("TAG", "onDestroy: " );
        if (currentWidget != null){
            currentWidget.terminatePlay();
        }
    }

    /**
     * 设置app运行时长
     */
    private void getLogTime() {
        logTime = (long) SPUtils.get(MainActivity.this,"LogTime",(long)0);
        SPUtils.remove(MainActivity.this,"LogTime");
        Timer  timer = new Timer();
        TimerTask  timerTask = new TimerTask() {
            @Override
            public void run() {
                long lastTime = (long) SPUtils.get(MainActivity.this,"LogTime",(long)0);
                SPUtils.put(MainActivity.this,"LogTime",lastTime+1000);
            }
        };
        timer.schedule(timerTask,1000,1000);
    }

    @SuppressLint("DefaultLocale")
    private String toMinute(long duration){

        return String.format("%.2f",duration/1000.0/60.0);
    }

    private long exitTime = 0;

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - exitTime > 2000){
            ToastUtils.show("再按一次退出应用");
            exitTime = System.currentTimeMillis();
        }else {
            System.exit(0);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void downloadFile(){
        if (data == null || data.getFiles() == null)
            return;
        if (downLoadPostion<data.getFiles().size()){
            String jsoned = (String) SPUtils.get(MainActivity.this,"CarcheFiles","");
            HashMap hashMaped ;
            if (TextUtils.isEmpty(jsoned)){
                hashMaped = new HashMap();
            }else {
                hashMaped = new Gson().fromJson(jsoned,HashMap.class);
            }
            TerminalApi.Bean.FilesDTO filesDTO = data.getFiles().get(downLoadPostion);
            if ("mp4".equals(filesDTO.getFileType())&&TextUtils.isEmpty((String) hashMaped.get(filesDTO.getFileId()))){

                File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), filesDTO.getFileName());
                Log.e("TAG", "downloadFile: "+file.getAbsolutePath().toString() );
                EasyHttp.download(this)
                        .method(HttpMethod.GET)
                        .file(file)
                        .url(filesDTO.getFilePath())
                        .listener(new OnDownloadListener() {
                            @Override
                            public void onStart(File file) {

                            }

                            @Override
                            public void onProgress(File file, int progress) {
                                Log.e("onProgress", "onProgress: "+ progress);
                            }

                            @Override
                            public void onComplete(File file) {
                                String json = (String) SPUtils.get(MainActivity.this,"CarcheFiles","");
                                if (TextUtils.isEmpty(json)){
                                    HashMap hashMap = new HashMap();
                                    hashMap.put(data.getFiles().get(downLoadPostion).getFileId(),file.getPath());
                                    SPUtils.put(MainActivity.this,"CarcheFiles",new Gson().toJson(hashMap));
                                }else{
                                    HashMap hashMap = new Gson().fromJson(json,HashMap.class);
                                    hashMap.put(data.getFiles().get(downLoadPostion).getFileId(),file.getPath());
                                    SPUtils.put(MainActivity.this,"CarcheFiles",new Gson().toJson(hashMap));
                                }
                                downLoadPostion++;
                                downloadFile();
                            }

                            @Override
                            public void onError(File file, Exception e) {
                                file.delete();
                                Log.e("TAG", "onError: " );
                            }

                            @Override
                            public void onEnd(File file) {

                            }
                        })
                .start();
            }else {
                downLoadPostion++;
                downloadFile();
            }
        }else{
            SPUtils.put(this,"locData",new Gson().toJson(data));
            //对比删除这次不存在的视频文件
            List<String> list = new ArrayList<>();//当前含有视频的集合
            for (TerminalApi.Bean.FilesDTO file:data.getFiles()) {
                if ("mp4".equals(file.getFileType())){
                    list.add(file.getFileId());
                }
            }
            String jsoned = (String) SPUtils.get(MainActivity.this,"CarcheFiles","");
            HashMap hashMaped ;
            if (TextUtils.isEmpty(jsoned)){
                hashMaped = new HashMap();
            }else {
                hashMaped = new Gson().fromJson(jsoned,HashMap.class);
            }
            List<String> list1 = new ArrayList<>();//已缓存视频集合
            for (Object key:hashMaped.keySet()) {
                list1.add((String) key);
            }
            if (list.size()>0){
                if (list1.size()>0){
                    List<String> reduceList = list1.stream().filter(item -> !list.contains(item)).collect(toList());
                    if (reduceList.size()>0){
                        for (String key:reduceList) {
                           String path = (String) hashMaped.get(key);
                           File file = new File(path);
                           file.delete();
                           hashMaped.remove(key);
                        }
                        SPUtils.put(MainActivity.this,"CarcheFiles",new Gson().toJson(hashMaped));
                    }
                }
            }else{//删除全部
                File file = new File(String.valueOf(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)));
                DeviceUtil.deleteDirWihtFile(file);
            }
        }

    }

}